/**
 * Copyright 2019 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.fos.oss;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import lombok.Data;

@Data
public class JSessionTokenPolicy {
//    {
//        "Version": "1",
//        "Statement": [{
//          "Action": ["oss:*"],
//          "Resource": ["acs:oss:*:*:*"],
//          "Effect": "Allow"
//        }]
//      }
    private String version;
    private Statement[] statements;

    @Data
    public static class Statement {
        String[] actions;
        String[] resources;
        String effect;
    }

    public String toPolicy() throws JSONException {
        JSONObject policy = new JSONObject();
        if (version != null) {
            policy.put("Version", version);
        }
        if (statements != null) {
            JSONArray array = new JSONArray();
            for (Statement statement : statements) {
                JSONObject item = new JSONObject();
                if (statement.actions != null) {
                    JSONArray actions = new JSONArray();
                    for (String action : statement.actions) {
                        actions.put(action);
                    }
                    item.put("Action", actions);
                }
                if (statement.resources != null) {
                    JSONArray resources = new JSONArray();
                    for (String resource : statement.resources) {
                        resources.put(resource);
                    }

                    item.put("Resource", resources);
                }
                if (statement.effect != null) {
                    item.put("Effect", statement.effect);
                }
                array.put(item);
            }
            policy.put("Statement", array);
        }
        return policy.toString();
    }
}
